package com.xsy.ftp;

import org.apache.commons.io.Charsets;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.BasePoolableObjectFactory;

import java.io.IOException;

public class FTPPoolAbleObjectFactory extends BasePoolableObjectFactory<FTPClient> {

    private FTPClientConfigure ftpClientConfigure;

    public FTPPoolAbleObjectFactory(FTPClientConfigure ftpClientConfigure) {
        this.ftpClientConfigure = ftpClientConfigure;
    }

    @Override
    public FTPClient makeObject() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(ftpClientConfigure.getClientTimeout());
        ftpClient.connect(ftpClientConfigure.getHost(),
                ftpClientConfigure.getPort());
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.out.println("FTPServer refused connection");
            return null;
        }
        boolean result = ftpClient.login(ftpClientConfigure.getUsername(),
                ftpClientConfigure.getPassword());
        if (!result) {
            throw new RuntimeException("ftpClient登陆失败");
        }
        ftpClient.setBufferSize(1024);
        ftpClient.setControlEncoding(ftpClientConfigure.getEncoding());
        ftpClient.setControlEncoding(Charsets.UTF_8.toString());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        if (ftpClientConfigure.getPassiveMode()) {
            ftpClient.enterLocalPassiveMode();
        }
        return ftpClient;
    }

    @Override
    public void destroyObject(FTPClient ftpClient) throws Exception {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            // 注意,一定要在finally代码中断开连接，否则会导致占用ftp连接情况
            try {
                ftpClient.disconnect();
            } catch (IOException io) {
                io.printStackTrace();
            }
        }
    }

    @Override
    public boolean validateObject(FTPClient ftpClient) {
        System.out.println("validateObject---------------");
        try {
            return ftpClient.sendNoOp();//
        } catch (IOException e) {
            System.out.println("Failed to validate client:");
            return false;
        }
    }


}